package com.home.qh.webapp.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.home.qh.model.CodeType;
import com.home.qh.model.Codes;
import com.home.qh.service.CodeTypeManager;
import com.home.qh.service.CodesManager;

@Controller
public class CodesController {
	private transient final Log log = LogFactory.getLog(CodesController.class);
	private CodesManager codesManager;
	private CodeTypeManager codeTypeManager;

	@Autowired
	private ApplicationContext context;

	@Autowired
	public void setCodesManager(CodesManager codesManager) {
		this.codesManager = codesManager;
	}

	@Autowired
	public void setCodeTypeManager(CodeTypeManager codeTypeManager) {
		this.codeTypeManager = codeTypeManager;
	}

	@RequestMapping(value = "/admin/codesList.*", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView listCities(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("entering 'handleRequest' method...");
		}

		Codes codesSearch = new Codes();
		String paramValue = request.getParameter("name");
		String paramCodeTypeValue = request.getParameter("codeType");
		if (paramValue != null && !"".equalsIgnoreCase(paramValue.trim())
				&& !"null".equalsIgnoreCase(paramValue)) {
			codesSearch.setCode(paramValue);
			codesSearch.setName(paramValue);
		}

		if (paramCodeTypeValue != null
				&& !"".equalsIgnoreCase(paramCodeTypeValue.trim())
				&& !"null".equalsIgnoreCase(paramCodeTypeValue)) {
			Long paramCodeTypeId = null;
			try {
				paramCodeTypeId = Long.parseLong(paramCodeTypeValue);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			if (paramCodeTypeId != null) {
				CodeType codeTypeSearch = codeTypeManager.get(paramCodeTypeId);				
				codesSearch.setCodeType(codeTypeSearch);
			}else{
				codesSearch.setCodeType(null);
			}
			

		}

		ModelAndView view = new ModelAndView("admin/codesList");
		view.addObject("codeTypeList", codeTypeManager.getAll());
		view.addObject("codesSearch", codesSearch);

		view.addObject("codesList",	codesManager.getCodesByCodes(codesSearch, null, false, -1, -1));
		return view;

	}

}
